package com.springboot.rookie.controller.system;

import com.springboot.rookie.pojo.SysMenuBean;
import com.springboot.rookie.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单信息
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController {
    @Autowired
    SysMenuService sysNavService;

    @GetMapping("/getAll")
    public List<SysMenuBean> getAll() {
        List<SysMenuBean> allList = sysNavService.getAll();
        //根导航
        List<SysMenuBean> navList = allList.stream()
                .filter(f -> StringUtils.isEmpty(f.getParentId()))
                .collect(Collectors.toList()
                );
        List<SysMenuBean> childList;
        for (SysMenuBean item : navList) {
            //二级导航
            childList = allList.stream()
                    .filter(f -> f.getParentId() == item.getId())
                    .collect(Collectors.toList());
            List<SysMenuBean> grandsonList;
            //三级导航
            for (SysMenuBean grandsonItem : childList) {
                grandsonList = allList.stream()
                        .filter(f -> f.getParentId() == grandsonItem.getId())
                        .collect(Collectors.toList());
                grandsonItem.setChildList(grandsonList);
            }

            item.setChildList(childList);
        }
        return navList;
    }

    @GetMapping("/getById")
    public SysMenuBean getById(Integer id) {
        return sysNavService.getById(id);
    }

    @PostMapping("/saveOrUpdate")
    public Boolean saveOrUpdate(SysMenuBean info) {
        //主键为null 添加，反之，更新
        if (info.getId() == null) {
            return sysNavService.save(info);
        } else {
            return sysNavService.updateSingle(info);
        }
    }

    @PostMapping("/delete")
    public Boolean deleteSingle(Integer id) {
        return sysNavService.removeById(id);
    }
}
